import 'package:boss/models/commodity.dart';
import 'package:boss/models/commission.dart';
import 'package:boss/ui/page/commission/page/commissionDetail/provider/commission_detail_provider.dart';
import 'package:boss/ui/page/commission/provider/commission_provider.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/bottomSheetPicker/show_bottom_sheet_picker.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/button/fixed_bottom_double_btn.dart';
import 'package:boss/ui/widget/calendar/calendar.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:boss/ui/widget/picker/commodityPicker/commodity_picker.dart';
import 'package:boss/ui/widget/picker/pickerStaff/picker_staff.dart';
import 'package:boss/ui/widget/picker/pickerTable/picker_table.dart';
import 'package:boss/ui/widget/radioList/radio_list_picker_util.dart';
import 'package:boss/ui/widget/timeRangePicker/time_range_picker.dart';
import 'package:boss/ui/widget/title_row_button.dart';

import 'package:hi_common/hi_common.dart';
import 'package:boss/util/time_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'under_btn_with_label.dart';

class CommissionDetailBrowser extends StatefulWidget {
  @override
  _CommissionDetailBrowserState createState() => _CommissionDetailBrowserState();
}

class _CommissionDetailBrowserState extends State<CommissionDetailBrowser> {
  List<SelectItem<String>> commissionWays;

  final List<SelectItem<int>> times = [
    SelectItem(title: '无期限', value: 0),
    SelectItem(title: '自定义时间', value: 1),
  ];

  CommissionDetailProvider provider;

  @override
  void initState() {
    super.initState();

    provider = Provider.of<CommissionDetailProvider>(context, listen: false);

    if (provider.commission.commissionType == Commission.COMMODITY) {
      commissionWays = [
        SelectItem(title: '原价百分比', value: Commission.ORI_PRICE_PERCENT),
        SelectItem(title: '售价百分比', value: Commission.SALE_PRICE_PERCENT),
        SelectItem(title: '固定金额', value: Commission.FIXED),
      ];
    } else {
      commissionWays = [
        // SelectItem(title: '单次预订', value: Commission.BOOK_NUM),
        // SelectItem(title: '实付百分比', value: Commission.PAY_AMOUNT_PERCENT),
        SelectItem(title: '桌数', value: Commission.TABLE_NUM),
        // SelectItem(title: '用餐人数', value: Commission.PERSON_NUM),
      ];
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Loader(
      loadTask: provider.loadData,
      builder: (context) => Consumer<CommissionDetailProvider>(
        builder: (context, provider, _) {
          return Column(
            children: <Widget>[
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(
                    horizontal: 25.w,
                  ),
                  child: Consumer<CommissionDetailProvider>(
                    builder: (context, provider, child) {
                      final commission = provider.commission;

                      return Column(
                        children: <Widget>[
                          BaseTextFormField(
                            prefixText: '提成名称',
                            isRequired: true,
                            hintText: '例如服务员酒水提成',
                            maxLength: 10,
                            initialValue: commission.commissionName,
                            onChanged: provider.setCommissionName,
                            enabled: provider.isEnabled,
                          ),
                          SelectFormField(
                            title: '提成方式',
                            isRequired: true,
                            items: commissionWays,
                            value: provider.commission.commissionWay,
                            onChanged: provider.setCommissionWay,
                            enabled: provider.isEnabled,
                            isHideIcon: !provider.isEnabled,
                          ),
                          BaseTextFormField(
                            prefixText: provider.commissionAmountTitle,
                            isRequired: true,
                            hintText: provider.commissionAmountHintText,
                            suffixText: provider.commissionAmountUnit,
                            keyboardType: TextInputType.numberWithOptions(decimal: true),
                            inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                            onChanged: provider.setCommissionAmount,
                            initialValue: provider.commission.amountText,
                            enabled: provider.isEnabled,
                          ),
                          if (provider.commission.commissionType == Commission.COMMODITY)
                            TitleRowButton(
                              title: '提成范围',
                              isRequired: true,
                              value: provider.commissionCommodityText,
                              onTap: selectCommoditys,
                              enabled: provider.isEnabled,
                              isHideIcon: !provider.isEnabled,
                            ),
                          if ((provider.commission?.commodityInfos?.length ?? 0) > 0)
                            UnderBtnWithLabel(
                              label: provider.commission.commodityNameText,
                              onTap: () => selectCommoditys(isSwitch: false),
                              enabled: provider.isEnabled,
                            ),
                          if (provider.commission.commissionType == Commission.BOOK)
                            TitleRowButton(
                              title: '提成桌台',
                              isRequired: true,
                              value: provider.commissionTableText,
                              onTap: pickerTable,
                              enabled: provider.isEnabled,
                            ),
                          if ((provider.commission?.tableInfos?.length ?? 0) > 0)
                            UnderBtnWithLabel(
                              label: provider.commission.tableNameText,
                              onTap: () => pickerTable(isSwitch: false),
                              enabled: provider.isEnabled,
                            ),
                          TitleRowButton(
                            title: '提成人群',
                            isRequired: true,
                            value: provider.commissionWaiterText,
                            onTap: pickerStaff,
                            enabled: provider.isEnabled,
                            isHideIcon: !provider.isEnabled,
                          ),
                          if ((provider.commission?.waiterInfos?.length ?? 0) > 0)
                            UnderBtnWithLabel(
                              label: provider.commission.waiterNameText,
                              onTap: () => pickerStaff(isSwitch: false),
                              enabled: provider.isEnabled,
                            ),
                          SelectFormField(
                            title: '提成时间',
                            isRequired: true,
                            items: times,
                            value: provider.timeType,
                            onChanged: provider.changeTimeType,
                            enabled: provider.isEnabled,
                            isHideIcon: !provider.isEnabled,
                          ),
                          if (provider.timeType == 1) ...[
                            TitleRowButton(
                              title: '日期',
                              hintText: provider.dateRangeText,
                              enabled: provider.isEnabled,
                              onTap: () async {
                                var res = await showCalendar(
                                  context,
                                  startDateTime: parseTime(provider.commission.beginDate),
                                  endDateTime: parseTime(provider.commission.endDate),
                                );

                                if (res != null) {
                                  provider.setDateRange(res[0], res[1]);
                                }
                              },
                            ),
                            TitleRowButton(
                              title: '时间',
                              hintText: provider.timeRangeText,
                              enabled: provider.isEnabled,
                              onTap: () async {
                                var res = await showTimeRangePicker(
                                  context,
                                  defaultValue: [provider.beginTimeIndex, provider.endTimeIndex],
                                );
                                if (res != null) {
                                  provider.setTimeRange(
                                    TimeUtil.int2TimeString(res[0]),
                                    TimeUtil.int2TimeString(res[1]),
                                  );
                                }
                              },
                            ),
                            TitleRowButton(
                              title: '星期',
                              hintText: provider.weekRangeText,
                              enabled: provider.isEnabled,
                              onTap: () async {
                                var res = await RadioListPickerUtil.weekday(context, value: provider.weekIndex);
                                if (res != null) {
                                  provider.setWeek(res);
                                }
                              },
                            ),
                          ]
                        ],
                      );
                    },
                  ),
                ),
              ),
              if (provider.commissionId == null)
                FixedBottomBtn(
                  title: '保存',
                  onTap: () => Provider.of<CommissionProvider>(context, listen: false).addCommission(provider.commission),
                ),
              if (provider.commissionId != null && provider.commissionStatus != Commission.END)
                FixedBottomDoubleBtn(
                  first: '复制',
                  second: '结束',
                  onFirst: Provider.of<CommissionDetailProvider>(context, listen: false).copy,
                  onSecond: () {
                    showAlert(
                      context,
                      content: '确定结束该提成方式吗？',
                      onCancel: (context) {
                        Navigator.pop(context);
                      },
                      onConfirm: (_) {
                        Provider.of<CommissionProvider>(context, listen: false).endCommission(provider.commission);
                      },
                    );
                  },
                ),
              if (provider.commissionId != null && provider.commissionStatus == Commission.END)
                FixedBottomBtn(
                  title: '复制',
                  onTap: Provider.of<CommissionDetailProvider>(context, listen: false).copy,
                ),
            ],
          );
        },
      ),
    );
  }

  DateTime parseTime(String value) {
    if (value == null) return null;

    return DateTime.parse(value);
  }

  selectCommoditys({bool isSwitch = true}) async {
    bool type = false;

    if (isSwitch) {
      type = await showBottomSheetPicker<bool>(
        context: context,
        items: [
          SelectItem(title: '全部菜品', value: true),
          SelectItem(title: '自定义菜品', value: false),
        ],
        value: provider.isAllCommodity,
      );
    }

    if (type == null) return;

    if (type) {
      provider.setCommissionCommoditys(null);
    } else {
      var selectedCommodity = provider.commission.commissionCommodityDOList
          ?.map((item) => Commodity.fromJson({
                'id': item.commodityId,
                'skuId': item.skuId,
                'sku': {
                  'skuId': item.skuId,
                }
              }))
          ?.toList();

      var res = await showCommodityPicker(
        context,
        isShowPackage: false,
        selectedCommodities: selectedCommodity,
        isShowSku: true,
      );

      if (res != null) {
        provider.setCommissionCommoditys(res);
      }
    }
  }

  pickerStaff({bool isSwitch = true}) async {
    bool type = false;

    if (isSwitch) {
      type = await showBottomSheetPicker<bool>(
        context: context,
        items: [
          SelectItem(title: '全部员工', value: true),
          SelectItem(title: '自定义员工', value: false),
        ],
        value: provider.isAllWaiter,
      );
    }

    if (type == null) return;

    if (type) {
      provider.setStaff(null);
    } else {
      var selectedId = provider.commission.commissionWaiterDOList?.map((item) => item.waiterId)?.toList();

      var res = await showPickerStaff(
        context,
        defaultSelectedId: selectedId,
        staffs: provider.staffs,
      );

      if (res != null) {
        provider.setStaff(res);
      }
    }
  }

  pickerTable({bool isSwitch = true}) async {
    bool type = false;

    if (isSwitch) {
      type = await showBottomSheetPicker<bool>(
        context: context,
        items: [
          SelectItem(title: '全部桌台', value: true),
          SelectItem(title: '自定义桌台', value: false),
        ],
        value: provider.isAllTable,
      );
    }

    if (type == null) return;

    if (type) {
      provider.setTable(null);
    } else {
      final selectedId = provider.commission.commissionTableDOList?.map((item) => item.tableId)?.toList();

      var res = await showPickerTable(
        context,
        defaultSelectedId: selectedId,
        tables: provider.tables,
      );
      if (res != null) {
        provider.setTable(res);
      }
    }
  }
}
